package com.ycx.ycxmybatismanagement.Interceptor;

import com.qiniu.rtc.model.RoomResult;
import com.ycx.ycxmybatismanagement.util.JwtUtils;
import com.ycx.ycxmybatismanagement.util.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //进入controLLer执行先进入preHandler，如果这个方法返回true，进入controLLer，如果是faLse，不进入controLler
//        log.info("pre{}",request.getRequestURI());
        //登录拦截
//        StringBuffer reqUrl = request.getRequestURL();
//        if (reqUrl.indexOf("/login")>=0){
//            return true;
//        }
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)){
            //表示没有值
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        if(!StringUtils.hasLength(token)){
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 校验token
        try{
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            //向当前线程保存一个UserInfo
            UserThreadLocal.setUserInfo(new UserThreadLocal.UserInfo(id,username));
            // token是合法的
            // 放行
           return true;
        }catch(Exception e){
            log.error(e.getMessage(), e);
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //controLLer执行完成以以后，会执行这个方法。
        // 如果controLL执行的时候出现异常，这个方法不执行
//        log.info("post{}",request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //页面渲染完成以后再执行
        // 就算controLL执行的时候出现异常，这个方法也要执行
//        log.info("after{}",request.getRequestURI());
    }
}
